<template>
  <div>
    <el-dialog :title="title" :visible="visible" @close="handleClose" width="800px">
      <el-form :model="frozen" label-position="right" ref="frozenRef" :rules="rules">
        <el-form-item label="修改前" prop="cstateid" :label-width="formLabelWidth">
          <el-select clearable v-model="frozen.cstateid">
            <el-option :disabled="isOptionDisabled(item)" v-for="(item, index) in frozenStatus" :key="index" :value="item.PK_STORESTATE"
              :label="item.name">
            </el-option>
          </el-select>
          <span style="margin-left: 30px;">可调整数量:{{maxNum}}</span>
        </el-form-item>
        <el-form-item label="调整数量" prop="nadjustnum" :label-width="formLabelWidth">
          <el-input @input="validateNumber" type="number" v-model="frozen.nadjustnum"></el-input>
        </el-form-item>
        <el-form-item label="修改后" prop="cadjuststateid" :label-width="formLabelWidth">
          <el-select clearable v-model="frozen.cadjuststateid" style="width: 100%;" @change="handleStateChangeAfter">
            <el-option :disabled="item.PK_STORESTATE === frozen.cstateid" v-for="(item, index) in frozenStatusAfter"
              :key="index" :value="item.PK_STORESTATE" :label="item.name">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table :data="frozenStatus">
        <el-table-column label="库存状态" prop="name"></el-table-column>
        <el-table-column label="数量">
          <template slot-scope="scope">
            <span>{{scope.row.unqualified_num}}</span>
            <span>{{scope.row.quarantine_num}}</span>
            <span>{{scope.row.qualified_num}}</span>
            <span>{{scope.row.limit_eligibility_num}}</span>
            <span>{{scope.row.research_num}}</span>
            <span>{{scope.row.qualified_no_use_num}}</span>
            <span>{{scope.row.pending_num}}</span>
            <span>{{scope.row.sku_no_state_num}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    updateState, //提交限制
    getStoStateInfo, //获取状态
    findTypeList, //获取类型
    findTableXXXSkuList, //批号限制
    findTypeAllByName //单据类型
  } from '@/api/storeM/index.js'

  export default {
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        rules: {
          cadjuststateid: [{
            required: true,
            message: '请选择修改后状态',
            trigger: 'blur'
          }, ],
        },
        frozen: {
          cstateid: '',
          cadjuststateid: '',
          nadjustnum: '',
          typeRestriction: '', // typeRestriction 为空时，表单项也会被清空
          //limitQuantity: '', // 用于限制数量
          //skuBarId: [], // 追溯码的SKU
          //typeMapId: [], // 单据类型
        },
        maxNum: 0,
        frozenType: [], //类型
        frozenStatusAfter: [],
        frozenStatus: [], //状态
        pkbathcodeList: [], //批号
        billList: [], //单据类型
        formLabelWidth: '68px',
        title: '修改状态',
        defaultProps: {
          children: 'children',
          label: 'skuBarId',
          id: 'skuBarId', // 使用 skuBarId 作为唯一标识
        },
      };
    },
    created() {
      this.getfindTypeAllByName(); // 获取单据类型
    },
    watch: {
      // 监听 selectedPKStorestate 的变化，更新对应的 num 字段
      'frozen.cstateid'(newVal) {
        this.updateCurrentNum(newVal)
      }
    },
    methods: {
      //获取单据类型list
      getfindTypeAllByName() {
        findTypeAllByName().then(res => {
          this.billList = res.data;
        })
      },
      //判断禁用
      isOptionDisabled(item) {
        // 查找以 _num 结尾的字段
        const numField = Object.keys(item).find(key => key.endsWith('_num'));
        if (numField) {
          return item[numField] === 0;
        }
        return false;
      },
      // 当用户输入数量时进行验证
      validateNumber(val) {
        let a = Number(val)
        if (a > this.maxNum) {
          this.frozen.nadjustnum = this.maxNum;
          this.$message('不能大于库存！！')
          return
        } else if (a < 0) {
          this.frozen.nadjustnum = 0;
          this.$message('不能小于0！！')
          return
        }
      },
      //获取追溯码list
      getBathCode() {
        let param = {
          pkMarbasclass: this.frozen.pkMaterial,
          pkBatchcode: this.frozen.pkBatchcode,
          cwarehouseId:this.frozen.cwarehouseid,
          cproductorId:this.frozen.cproductorid
        }
        findTableXXXSkuList(param).then(res => {
          if (res.msg == '该表不存在') {
            this.frozenType = this.frozenType.filter(item => item.id !== 3);
          } else {
            this.pkbathcodeList = res.data;
          }
        })
      },
      //获取类型list
      getTypeList() {
        findTypeList().then(res => {
          this.frozenType = res.data;
        })
      },
      handleCheckChange(checkedKeys) {
        const checkedNodes = this.$refs.treeRef.getCheckedNodes();
        this.frozen.skuBarId = checkedNodes.map(item => item.skuBarId);
      },
      updateCurrentNum(PKStorestate) {
        // 查找数据中与选中的 PK STORESTATE 对应的项
        for (let key in this.frozenStatus) {
          if (this.frozenStatus[key]["PK_STORESTATE"] === PKStorestate) {
            // 根据不同的 key 来设置对应的 num
            //不合格
            if (this.frozenStatus[key]["unqualified_num"] !== undefined) {
              this.frozen.nadjustnum = this.frozenStatus[key]["unqualified_num"];
              this.maxNum = this.frozen.nadjustnum;
            } else if (this.frozenStatus[key]["quarantine_num"] !== undefined) {
              //待验
              this.frozen.nadjustnum = this.frozenStatus[key]["quarantine_num"];
              this.maxNum = this.frozen.nadjustnum;
            } else if (this.frozenStatus[key]["qualified_num"] !== undefined) {
              //合格
              this.frozen.nadjustnum = this.frozenStatus[key]["qualified_num"];
              this.maxNum = this.frozen.nadjustnum;
            } else if (this.frozenStatus[key]["limit_eligibility_num"] !== undefined) {
              //限制合格
              this.frozen.nadjustnum = this.frozenStatus[key]["limit_eligibility_num"];
              this.maxNum = this.frozen.nadjustnum;
            }else if(this.frozenStatus[key]["research_num"] !== undefined){
              //研究用
              this.frozen.nadjustnum = this.frozenStatus[key]["research_num"];
              this.maxNum = this.frozen.nadjustnum;
            }else if(this.frozenStatus[key]["qualified_no_use_num"] !== undefined){
              //合格不予上市
              this.frozen.nadjustnum = this.frozenStatus[key]["qualified_no_use_num"];
              this.maxNum = this.frozen.nadjustnum;
            }else if(this.frozenStatus[key]["pending_num"] !== undefined){
              //待处理
              this.frozen.nadjustnum = this.frozenStatus[key]["pending_num"];
              this.maxNum = this.frozen.nadjustnum;
            }
            break;
          }
        }
      },
      //获取状态list
      getStateList() {
        let param = {
          cmaterialoid: this.frozen.pkMaterial,
          pkBatchcode:this.frozen.pkBatchcode,
          vbatchcode: this.frozen.vbatchcode,
          cwarehouseid:this.frozen.cwarehouseid,
          cproductorid:this.frozen.cproductorid,
          // vbillcode:this.frozen.vbillcode
        }
        getStoStateInfo(param).then(res => {
          // 假设 frozenStatus 是一个数组
          if (res.data && Object.keys(res.data).length > 0) {
              this.frozenStatus = Array.isArray(res.data.type1)
                  ? res.data.type1
                  : Object.values(res.data.type1);
          } else {
              this.frozenStatus = []; // 或者其他默认值
          }
          if (res.data && Object.keys(res.data).length > 0) {
              this.frozenStatusAfter = Array.isArray(res.data.type2)
                  ? res.data.type2
                  : Object.values(res.data.type2);
          } else {
              this.frozenStatusAfter = []; // 或者其他默认值
          }
          this.updateCurrentNum(this.frozen.cstateid);
        })
      },
      //获取信息
      openDiolog(row) {
        if (row) {
          this.frozen.pkMaterial = row.pk_material; //给追溯码用的
          this.frozen.pkBatchcode = row.pk_batchcode;//批号
          this.frozen.vbatchcode = row.vbatchcode;//批次号
          this.frozen.updateType = row.updateType;//修改类型
          this.frozen.crowno = row.crowno?row.crowno:'';//行号
          this.frozen.cgeneralbid = row.cgeneralbid?row.cgeneralbid:'';
          this.frozen.cwarehouseid = row.cwarehouse_id?row.cwarehouse_id:'';//仓库id
          this.frozen.cproductorid = row.pk_product?row.pk_product:'';//生产厂商
          this.frozen.stoId = row.sto_id?row.sto_id:'';//仓库id
          this.frozen.name = row.name;//商品名称
          this.getStateList();
        }
      },
      //关闭弹出
      handleClose() {
        this.$emit('update:visible', false);
        this.$nextTick(() => {
          this.$refs.frozenRef.resetFields();
        })
      },
      //修改状态
      submit() {
        this.$refs.frozenRef.validate((valid) => {
          if (valid) {
            let params = {
              cadjuststateid: this.frozen.cadjuststateid,
              cstateid: this.frozen.cstateid,
              cmaterialoid: this.frozen.pkMaterial,
              vbatchcode: this.frozen.vbatchcode,//批号
              nadjustnum: this.frozen.nadjustnum,//修改数量
              updateType: this.frozen.updateType,//修改类型
              pkMaterial:this.frozen.pkMaterial,//商品pk
              cgeneralbid:this.frozen.cgeneralbid,
              crowno:this.frozen.crowno,//行号
              cwarehouseid:this.frozen.cwarehouseid,//仓库
              cproductorid:this.frozen.cproductorid,//生产厂商
              stoId:this.frozen.stoId,//仓库id
              name: this.frozen.name,//商品名称
            }
            const apiMethod = updateState;
            apiMethod(params).then(res => {
              this.$message({
                message: res.msg,
                type: 'success',
              });
              this.$emit('successfun');
              this.handleClose();
            }).catch(err => {
              this.$message({
                message: err?.msg || '操作失败',
                type: 'error',
              });
            });
          } else {
            return false;
          }
        });
      },
      //修改后的状态select
      handleStateChangeAfter(data) {
        this.frozen.cadjuststateid = data;
      },
    },
  };
</script>

<style scoped>
  /deep/.el-tree {
    height: 300px;
    overflow: auto;
  }
</style>
